package com.sxfq.loansupermarket.backsystem.modular.doctorLooked.controller;

import com.baomidou.mybatisplus.plugins.Page;
import com.sxfq.loansupermarket.backsystem.common.constant.factory.PageFactory;
import com.sxfq.loansupermarket.backsystem.common.controller.BaseController;
import com.sxfq.loansupermarket.backsystem.core.log.LogManager;
import com.sxfq.loansupermarket.backsystem.core.log.factory.LogTaskFactory;
import com.sxfq.loansupermarket.backsystem.core.shiro.ShiroKit;
import com.sxfq.loansupermarket.backsystem.core.support.HttpKit;
import com.sxfq.loansupermarket.backsystem.modular.doctorLooked.entity.SearchTechnologyProcessingInfo;
import com.sxfq.loansupermarket.backsystem.modular.doctorLooked.entity.TechnologyProcessingInfo;
import com.sxfq.loansupermarket.backsystem.modular.doctorLooked.service.ITechnologyProcessingService;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.List;

/**
 * 医生回访
 *
 * @author py
 * @Date 2018年4月19日23:15:54
 */
@Controller
@RequestMapping("/technologyProcessing")
public class TechnologyProcessingController extends BaseController {
    @Autowired
    ITechnologyProcessingService service;
    @Autowired
    private RedisTemplate redisTemplate;
    private String PREFIX = "/doctorLooked/";

    // 跳转到技加工耗材
    @RequestMapping("")
    public String consultant(Model model) {
        String tableHead = redisTemplate.opsForList().index(ShiroKit.getUser().getAccount()+"Abbreviation",0)+"";
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        model.addAttribute("outpatientManagementList", ShiroKit.getSessionAttr("outpatientManagementList"));
        model.addAttribute("userName", ShiroKit.getUser().getAccount());
        return PREFIX + "technologyProcessing.html";
    }

    // 技加工
    @RequestMapping("/list")
    @ResponseBody
    public Object testrInfoList(SearchTechnologyProcessingInfo info, HttpServletRequest request) {
        Page<TechnologyProcessingInfo> page = new PageFactory<TechnologyProcessingInfo>().defaultPage();
        try {
            info.setStartIndex(page.getSize() * (page.getCurrent() - 1));
            info.setLimitIndex(page.getSize());
            page.setCurrent(0);
            List<TechnologyProcessingInfo> list = service.selectPageListByQueryGetMap(page, info);
            if (list.size() == 0) {
                info.setStartIndex(0);
                list = service.selectPageListByQueryGetMap(page, info);
            }
            page.setTotal(service.getQueryPagesCount(page, info));
            page.setRecords(list);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return super.packForBT(page);
    }

    // 技加工导出
    @RequestMapping(value = "/technologyProcessingExport")
    public void technologyProcessingExport(@RequestParam(required = false) String reach,@RequestParam(required = false) String startTime,
                                      @RequestParam(required = false) String endTime,@RequestParam(required = false) String arrivalStore,
                                      HttpServletResponse response) {
        try {
            SearchTechnologyProcessingInfo searchInfo = new SearchTechnologyProcessingInfo();
            searchInfo.setStartTime(startTime);
            searchInfo.setEndTime(endTime);
            searchInfo.setReach(reach);
            searchInfo.setArrivalStore(arrivalStore);
            List<TechnologyProcessingInfo> list = service.technologyProcessingExport(searchInfo);
            // 解析成excel文件
            // 第一步，创建一个webbook，对应一个Excel文件
            HSSFWorkbook wb = new HSSFWorkbook();
            // 第二步，在wb中添加一个sheet,对应Excel文件中的sheet
            HSSFSheet sheet = wb.createSheet("前端导出");
            for (int i = 0; i < 19; i++) {
                sheet.setColumnWidth(i, 24 * 256);
            }
            // 第三步，在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
            HSSFRow row = sheet.createRow(0);
            // 第四步，创建单元格，并设置值表头 设置表头居中
            HSSFCellStyle style = wb.createCellStyle();
            style.setAlignment(HorizontalAlignment.CENTER);// 创建一个居中格式
            HSSFCell cell = row.createCell(0);
            cell.setCellValue("病历号");
            cell.setCellStyle(style);
            cell = row.createCell(1);
            cell.setCellValue("患者姓名");
            cell.setCellStyle(style);
            cell = row.createCell(2);
            cell.setCellValue("电话");
            cell.setCellStyle(style);
            cell = row.createCell(3);
            cell.setCellValue("性别");
            cell.setCellStyle(style);
            cell = row.createCell(4);
            cell.setCellValue("年龄");
            cell.setCellStyle(style);
            cell = row.createCell(5);
            cell.setCellValue("耗材名称");
            cell.setCellStyle(style);
            cell = row.createCell(6);
            cell.setCellValue("原价");
            cell.setCellStyle(style);
            cell = row.createCell(7);
            cell.setCellValue("数量");
            cell.setCellStyle(style);
            cell = row.createCell(8);
            cell.setCellValue("折后金额");
            cell.setCellStyle(style);
            cell = row.createCell(9);
            cell.setCellValue("所属类型");
            cell.setCellStyle(style);
            cell = row.createCell(10);
            cell.setCellValue("创建时间");
            cell.setCellStyle(style);
            cell = row.createCell(11);
            cell.setCellValue("医生");
            cell.setCellStyle(style);
            cell = row.createCell(12);
            cell.setCellValue("门诊");
            cell.setCellStyle(style);
            cell = row.createCell(13);
            cell.setCellValue("加工单位");
            cell.setCellStyle(style);
            cell = row.createCell(14);
            cell.setCellValue("订单状态");
            cell.setCellStyle(style);
            cell = row.createCell(15);
            cell.setCellValue("备注");
            cell.setCellStyle(style);
            // 填充数据
            for (int i = 0; i < list.size(); i++) {
                TechnologyProcessingInfo map = list.get(i);
                row = sheet.createRow(i + 1);
                String medicalRecordNumber = map.getMedicalRecordNumber();
                String customerName = map.getCustomerName();
                String customerPhone = map.getCustomerPhone();
                String customerSex = map.getSex();
                String customerAge = map.getCustomerAge();
                String payServiceName = map.getPayServiceName();
                String amount = map.getAmount();
                String number = map.getNumber();
                String discountPrice = map.getDiscountPrice();
                String type = map.getType();
                String createTime = map.getCreateTime();
                String doctor = map.getDoctor();
                arrivalStore = map.getArrivalStore();
                String processUnit = map.getProcessUnit();
                String status = map.getStatus();
                String remarks = map.getRemarks();
                // 第四步，创建单元格，并设置值
                for (int j = 0; j <= 15; j++) {
                    row.createCell(j).setCellStyle(style);
                }
                row.getCell(0).setCellValue(medicalRecordNumber);
                row.getCell(1).setCellValue(customerName);
                row.getCell(2).setCellValue(customerPhone);
                row.getCell(3).setCellValue(customerSex);
                row.getCell(4).setCellValue(customerAge);
                row.getCell(5).setCellValue(payServiceName);
                row.getCell(6).setCellValue(amount);
                row.getCell(7).setCellValue(number);
                row.getCell(8).setCellValue(discountPrice);
                row.getCell(9).setCellValue(type);
                row.getCell(10).setCellValue(createTime);
                row.getCell(11).setCellValue(doctor);
                row.getCell(12).setCellValue(arrivalStore);
                row.getCell(13).setCellValue(processUnit);
                row.getCell(14).setCellValue(status);
                row.getCell(15).setCellValue(remarks);
            }
            String date = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new java.util.Date());
            String filename = "data" + date + ".xls";
            response.setHeader("Content-Disposition",
                    "attachment; filename=\"" + URLEncoder.encode(filename, "UTF-8") + "\"");
            response.setContentType("application/octet-stream;charset=UTF-8");
            OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
            wb.write(outputStream);
            outputStream.flush();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}